package com.study.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.study.entity.db1.UserInfoPO;
import com.study.entity.db2.User2PO;
import com.study.mapper.db1.UserInfoMapper;
import com.study.mapper.db2.User2Mapper;
import com.study.service.IUserInfoService;
import com.study.util.BaseUtils;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private User2Mapper user2Mapper;

	@Autowired
	private PlatformTransactionManager transactionManager;

	@Override
	public List<UserInfoPO> queryAllUser() {
		return userInfoMapper.queryAllUser();
	}

	@Override
	public UserInfoPO findUserInfoByLoginNameAndPassword(String loginName, String pwd) {
		return userInfoMapper.findUserInfoByLoginNameAndPassword(loginName, pwd);
	}

	@Override
	public void saveUser(Map<String, Object> paramMap) {
		TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
		// 获取事务，开始业务执行
		TransactionStatus transaction = transactionManager.getTransaction(transactionDefinition);

		try {
			UserInfoPO userInfo = BaseUtils.mapToEntity(paramMap, UserInfoPO.class);
			userInfoMapper.saveUser(userInfo);

			User2PO user2 = BaseUtils.mapToEntity(paramMap, User2PO.class);
			user2Mapper.saveUser(user2);

			transactionManager.commit(transaction);
		} catch (Exception e) {
			transactionManager.rollback(transaction);
			throw new RuntimeException(e.getMessage());
		}
	}

}
